 var app;
 var nl2br = function(str, is_xhtml) {   
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
 	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
 };

var icon = function(file, className) {
	return '<img src="'+ path() + 'img/icons/' + file +'"'+(className?'class="'+className+'"':'')+'>';
}
 $(document).ready(function() {

	jQuery.getScript( path() + 'js/jquery.center.js');
	jQuery.getScript( path() + 'js/autoresize.jquery.min.js');
	jQuery.getScript( path() + 'js/vimeo-srt-api.js'); 
	jQuery.getScript( path() + 'js/jquery.download.js');
	jQuery.getScript( path() + 'js/utf8.js'); 
	jQuery.getScript( path() + 'js/jquery.vimeosrt.js'); 
	jQuery.getScript( path() + 'js/jquery.scrollTo-1.4.2-min.js'); 
	jQuery.getScript( path() + 'js/DropTarget.js');
	
	app = new SrtEditor($('.editor.panel .panel-content')); 
	app.element.bind('srtLoaded', function() {
		$('h3.top-header').text( app.currentSrt );
	});
	//-------------------------------------------------------------------
	//
	// load additional script files
	//
	//-------------------------------------------------------------------  
	
	
	//-------------------------------------------------------------------
	//
	// init UI
	//
	//-------------------------------------------------------------------
   
	$('.button.loadDefaults').click(function(e) {
		e.preventDefault();
		app.loadDefaults();
	});  
	
	 
	$('.button.text-bigger').click(function(e) {
		e.preventDefault();
		app.displayFontSize(1)
	});  
	$('.button.text-smaller').click(function(e) {
		e.preventDefault();
		app.displayFontSize(-1)
	});  
	$('.button.loadCustom').click(function(e) {
		app.showLoadDialog();
	});   
	$('.button.saveSrt').click(function(e) { 
		var srt = app.srtParser.generate( app.lines );
		var win;
		if (typeof win == 'undefined' || win.closed)
			win = window.open()
 
			var doc = win.document;
			doc.open();
			doc.write(
				'<html>'
				+'	<head>'
				+'		<meta charset=utf-8 />'
				+'		<title>SRT Editor</title>'
				+'	</head>'
				+'	<body style="font-family:Courier New, Courier;font-size:11px;">'
				+ 	nl2br(srt)
				+'	</body>'
				+'</html>'
			);
			doc.close();
			win.focus();
	});   
	setTimeout(app.onresize, 100);
	$(window).resize(app.onresize);  
	
	//app.loadDefaults();
});

 
 var PreviewPanel = function() {
	 this.srtPlayerUrl = path()+'/swf/VimeoSrtPlayer.swf?_='+new Date().getTime(); 
	 this.createView();
	 this.settings = {
		srtFontSize: 13,
		srtMargin: 10
	 }
	 window.onSubtitleApiReady = delegate(this, this.onSubtitleApiReady);
	
 }
 PreviewPanel.prototype = {
		 
	//---------------------------------------------------------------------------------------------
	// 
	// CREATE ELEMENTS
	//
	//---------------------------------------------------------------------------------------------
		 
	createView: function() {	
		var self = this;
		
		/* element */
	 	var element = $('<div class="vimeo panel">');
	 	element.hide();
	 	element.draggable();
	 	element.resizable({ 
	 		resize: delegate(this, this.onResize),
	 		minWidth: 320,
	 		minHeight: 240,
	 		stop: function() { element.css('position', 'fixed'); }
	 	});
	 	element.css('position', 'fixed');
		this.element = element;
	 	
	 	/* title */
		element.append($('<h3><a title="Toggle video">vimeo url</a></h3>)'));
	 	
	 	/* iframe */
		element.append($('<div class="player"><iframe width="400" height="225" frameborder="0"></div>'));
		var iframe = element.find('iframe');
		this.iframe = iframe;
		
		
	 	/* buttons */
		element.append($('<div class="controls" style="overflow:hidden">'
	 		
	 		/* left side buttons */
			+'<div style="float:left"><div class="buttons">'
			+'<a class="decrease fontsize" title="Decrease text size"><span>'+icon('text-smaller.gif')+'</span></a>'
			+'<a class="increase fontsize" title="Increase text size"><span>'+icon('text-bigger.gif')+'</span></a>'
			+'<a class="increase margin" title="Text position up"><span>'+icon('arrow-up.gif')+'</span></a>'
			+'<a class="decrease margin" title="Text position down"><span>'+icon('arrow-down.gif')+'</span></a>'
			+'<a class="reset" title="Reset size and position"><span>'+icon('undo.gif')+'</span></a>'
			+'</div></div>' 
			
			/* right side buttons */
			+'<div style="float:right"><div class="buttons">'
			+'<a class="edit line" title="Edit current text line"><span>'+icon('edit.gif')+'</span></a>'
			+'<a class="autoscroll" title="Enable automatic scrolling"><span><input type="checkbox"><span>'+icon('lock.gif')+'</span></span></a>'
			+'</div></div>'
		));

		/* events */ 	
		element.find('.increase.fontsize').click(function(e) { self.changeTextSize(1); });		
		element.find('.decrease.fontsize').click(function(e) { self.changeTextSize(-1); });		
		element.find('.increase.margin').click(function(e) { self.changeTextMargin(1); });
		element.find('.decrease.margin').click(function(e) { self.changeTextMargin(-1); });
		element.find('.reset').click(function(e) { self.resetText(); }); 
		element.find('.edit').click(function(e) { element.trigger('editClick', [e]); });  
		element.find('.autoscroll').click(function(e) { self.fixCheckButton(e) }); 
		element.find('.autoscroll input').change(function(e) {self.toggleAutoscroll()});   
		iframe.load(function(e) {
			element.trigger('frameLoaded');
		});
 
 	},

	//---------------------------------------------------------------------------------------------
	// 
	// LOADING
	//
	//---------------------------------------------------------------------------------------------
 	
 	load: function(vim,srt,srtData) {
 		//console.log('preview.load('+vim+', '+srt+')');
 		var self = this;
 		var onFrameLoaded = function() {
 			if (srt) { self.loadSrt(srt); }
 			else if (srtData) { self.setSrtData(srtData); }
 			self.element.unbind('frameLoaded', onFrameLoaded);
 		}
 		this.element.bind('frameLoaded', onFrameLoaded)
 		this.loadVimeo(vim);
 	},
 	
 	loadVimeo: function(id) { 
 		//console.log('preview.loadVimeo('+id+')');
 		var clip_id = id || window.prompt('Vimeo url or ID'); 
 		if (isNaN(clip_id)) { clip_id = clip_id.substr(clip_id.lastIndexOf('/')+1, clip_id.length);	}
 		if (!clip_id) {	return;	}

 		this.clip_id = clip_id;
 		this.iframe.attr('src', 'http://player.vimeo.com/video/'+clip_id); 		
 		this.element.find('h3 a').text( this.iframe.attr('src') );
 		this.element.show();
 	}, 
 	
 	loadSrt: function(file) { 
 		//console.log('preview.loadSrt('+file+')')
 		this.currentSrt = file;
 		this.iframe.vimeosrt({
 			swf: this.srtPlayerUrl,
 			srt: file,
 			srtFontSize: this.settings.srtFontSize,
 			srtMargin: this.settings.srtMargin
 		});
 	}, 
 	
 	setSrtData: function(srt_str) { 
 		//console.log('preview.setSrtData()',srt_str)
 		this.currentSrtData = srt_str;
 		this.iframe.vimeosrt({
 			swf: this.srtPlayerUrl,
 			srtData: srt_str,
 			srtFontSize: this.settings.srtFontSize,
 			srtMargin: this.settings.srtMargin
 		});
 	},

	//---------------------------------------------------------------------------------------------
	// 
	// HANDLE EVENTS
	//
	//---------------------------------------------------------------------------------------------

 	/*
 	 * gets called when VimeoSrtPlayer is ready
 	 */
 	onSubtitleApiReady: function() {  
 		this.swf = this.element.find('object')[0];
 		this.element.trigger('subtitleApiReady');
 	}, 
 	onResize: function() {
 		var header = this.element.find('h3');
 		var player = this.element.find('.player');
 		var controls = this.element.find('.controls');
 		player.height( this.element.height() - controls.height() - header.height() - 10);
 		
 		if (this.swf) {
 			var swf_w = this.element.width() - 20;
 			var swf_h = player.height() - 20;
 			$(this.swf).width(swf_w);
 			$(this.swf).height(swf_h);
 			//
 	 		//this.swf.setSize( swf_w, swf_h ); 
 		}
 	},
 	
 	
 	
 	
 	
 	
 	
 	

	//---------------------------------------------------------------------------------------------
	// 
	// MINOR STUFF / MISC
	//
	//---------------------------------------------------------------------------------------------
 	
 	changeTextSize: function(v) {  
 		if (!this.swf) return;
		var s = this.swf.getFontSize();
		s += v;
		if (s > 30) { s = 30; }
		if (s < 1) { s = 1; }
		this.swf.setFontSize(s);
	},
	
	changeTextMargin: function(v) {  
 		if (!this.swf) return;
		var m = this.swf.getFontMargin();
		m += v;
		if (m > 50) { m = 50; }
		if (m < 1) { m = 1; }
		this.swf.setFontMargin(m);
	},
	
	resetText: function() { 
 		if (!this.swf) return;
		this.swf.setFontMargin(this.settings.srtMargin);
		this.swf.setFontSize(this.settings.srtFontSize);
	},
	
 	/* synchronises button and checkbox, hack */
 	fixCheckButton: function(e) {
 		if ($(e.target).attr('type')=='checkbox') {
 			return;
 		}
 		e.preventDefault();
 		var c = $(e.currentTarget).find('input');
 		c.attr('checked', !c.attr('checked'));
 		c.change();
 	},
 	
 	toggleAutoscroll: function() { 
 		var checked = this.element.find('.autoscroll input').attr('checked');
 		this.element.find('.autoscroll')[(checked?'add':'remove')+'Class']('active'); 
 	}
 }
 var SrtEditor = function(element) {
	 if (SrtEditor.instance) {
		 return alert('Only one instance of SrtEditor is allowed!')
	 }

	 SrtEditor.instance = this;
	 
	 this.defaultSrt = path() + 'sample-files/srt/1603_de_lars.srt?time='+new Date().getTime();
	 this.defaultSrt = path() + 'sample-files/srt/example.srt?time='+new Date().getTime();
	 this.defaultVimeo = 17712557;

	 this.element = element;
	 this.srtParser = new SrtParser(); 
	 this.originalLines = [];
	 this.lines = [];
	 $('html').addClass('zoom-3');
	 
	 this.createView();
	 
 };
 
 
 SrtEditor.prototype = { 
		 
	loadDefaults: function() {	 
	 	this.display(this.defaultSrt, this.defaultVimeo)
 	},

 	
 	log: function(msg) {
 		if (window.hasOwnProperty('console')) {
 			console.log(msg);
 		}
 	},
 	
 	//---------------------------------------------------------------------------------------------
 	//
 	// VIEW AND ELEMENTS
 	//
 	//---------------------------------------------------------------------------------------------
 	
 	/**
 	 * Creates the view elements.
 	 */
 	createView: function() { 
 		
 		var self = this;
 		
 		//--------------------------------------
 		// create table
 		//--------------------------------------
 		this.table = this.createTable(); 
 		this.table.appendTo(this.element);
 		
 		 
 		//--------------------------------------
 		// create preview
 		//--------------------------------------
 		this.element.append( $('<div class="buttons" style="margin-top:10px"><a class="add-new" style="float:right"><span>Create new line</span></a></div>') )
 		this.element.find('.add-new').click(delegate(this, this.addRow));
 		this.preview = new PreviewPanel();
 		this.preview.element.appendTo( $('#app') );  
 		this.preview.element.bind('editClick',delegate(this, this.editCurrentLine));
 		
 		this.preview.element.bind('subtitleApiReady', function() {
 	 		srtapi.addListener(self.preview.swf, 'subtitleText', function(e) { 
 	 			self.onPlayerSubtitleChange(e);
 	 		});
 		}); 
 	}, 
 	
 	/**
 	 * Creates the table but not the rows (rows are created in updateRows() )
 	 * @return table element
 	 */
 	createTable: function() {
 		var table = $('<table class="datatable">');
 		table.append($('<thead>'));
 		table.find('thead').append( $('<tr>'));
 		table.find('thead tr').append( $('<th class="id">').text('Nr') );
 		table.find('thead tr').append( $('<th class="start">').text('Time in') );
 		table.find('thead tr').append( $('<th class="end">').text('Time out') );
 		table.find('thead tr').append( $('<th class="text">').text('Text') );  
 		table.find('thead tr').append( $('<th class="actions">').text('Actions') ); 
 		table.append($('<tbody>'));
 		return table;
 	},
 	
 	/**
 	 * Creates a single table row
 	 * @param line a subtitle line object
 	 * @return tr element
 	 */
 	createTableRow: function(line) {
 		var comp_id = this.currentLineCount;
 		var tr = $('<tr class="datarow row-'+comp_id+'" id="line-'+comp_id+'">'); 
		tr.append(
			'<td class="id">'
			+'	<span>'+comp_id+'</span>' + icon('caution.gif', 'caution')
			+'</td>'
			+'<td class="start">'
			+'	<div class="display">' + icon('edit.gif') + '<span class="value">'+line.start+'</span></div>'
			+'	<div class="edit">'
			+'		<input type="text" class="input textfield">'
			+'		<div class="buttons">'
			+'			<a class="cancel"><span>'+icon('against.gif')+'</span></a>'
			+'			<a class="save"><span>'+icon('checkmark.gif')+'</span></a>'
			+'		</div>'
			+'	</div>'
			+'</td>'
			+'<td class="end">'
			+'	<div class="display">' + icon('edit.gif') + '<span class="value">'+line.end+'</span></div>'
			+'	<div class="edit">'
			+'		<input type="text" class="input textfield">'
			+'		<div class="buttons">'
			+'			<a class="cancel"><span>'+icon('against.gif')+'</span></a>'
			+'			<a class="save"><span>'+icon('checkmark.gif')+'</span></a>'
			+'		</div>'
			+'	</div>'
			+'</td>'
			+'<td class="text">'
			+'	<div class="display">' + icon('edit.gif') + '<span class="value">'+this.lineToHtml(line.text)+'</span></div>'
			+'	<div class="edit">'
			+'		<textarea class="input textfield"></textarea>'
			+'		<div class="buttons">'
			+'			<a class="cancel"><span>'+icon('against.gif')+'</span></a>'
			+'			<a class="save"><span>'+icon('checkmark.gif')+'</span></a>'
			+'		</div>'
			+'	</div>'
			+'</td>'
			+'<td class="actions">'
			+'	<div class="buttons">'
			+'		<a class="button move up" title="Move line up"><span>'+icon('arrow-up.gif')+'</span></a>'
			+'		<a class="button add before" title="Insert line before"><span>'+icon('plus-arrow-up.gif')+'</span></a>'
			+'		<a class="button delete" title="Delete line"><span>'+icon('trash.gif')+'</span></a>'
			+'	</div>'
			+'	<div class="buttons">'
			+'		<a class="button move down" title="Move line down"><span>'+icon('arrow-down.gif')+'</span></a>'
			+'		<a class="button add after" title="Insert line after"><span>'+icon('plus-arrow-down.gif')+'</span></a>'
			+'	</div>'
			+'</td>'
				
		); 
		this.markErrors(tr);
		tr.find('textarea').autoResize();
		return tr;
 	},

 	updateRows: function() {
 
 		var tim = new Date().getTime(); 
 		this.log('updateRows()');
		
 		//----------------------------------------
 		// vars
 		//----------------------------------------
 		this.currentLineCount = 0;
 		
 		var self = this;
 		var rowsPerStep = 5; 		
 		var lns = this.lines; 		
 		var t = lns.length;
 		var i=0;
 		var tb = this.table.find('tbody');
 		
 		//----------------------------------------
 		// pre-initialize
 		//----------------------------------------
		this.disableView();
		$('#overlay .inner').show();
		$('#overlay .progress').show();
		$('#overlay .title').text('creating table rows')
 		tb.empty(); 
 		tb.remove(); 

 		//----------------------------------------
 		// action
 		//----------------------------------------

 		/**
 		 * Called when all rows have been created 
 		 * @returns
 		 */
 		var complete = function() {
 			
			// attach event handlers
	 		tb.find('.display').dblclick(delegate(self, self.beginEdit)); 
	 		tb.find('.display img').click(delegate(self, self.beginEdit)); 
	 		tb.find('.cancel').click(delegate(self, self.endEdit));
	 		tb.find('.save').click(delegate(self, self.saveEdit));
	 		tb.find('.add').click(delegate(self, self.addRow)); 
	 		tb.find('.delete').click(delegate(self, self.deleteRow)); 
	 		
	 		// attach table body and enable view
			self.table.append(tb);	
	 		self.enableView();
 
	 		// trigger an event
	 		self.table.trigger('update');  
	 		self.onTableUpdated();
 		}
 		/**
 		 * Called in an interval loop
 		 */
 		var onStep = function() {
 			
 			// create and append row(s)
 			for (var _i=0; _i<rowsPerStep; _i++) {
 				var line = lns[i+_i];
 				if (line) {
 		 			self.currentLineCount++; 
	 	 			var tr = self.createTableRow(line);
	 	 			tr.find('.edit').hide();
	 	 			tb.append(tr);
 				}
 			}
 			
 			i += rowsPerStep;
 			$('#overlay .status').text(i+' of '+t+' lines done'); 
 			$('#overlay .progress .fill').css('width', (i/t*100)+'%')
 			if ( i>=t ) {
 	 			// clear the interval
 				window.clearInterval(self.stepInt);

 				// status messages
 				$('#overlay .title').text(t+' lines created in '+(new Date().getTime()-tim)+'ms')
 	 			$('#overlay .status').text('...please wait...'); 
 		 		self.log(t+' lines created in '+(new Date().getTime()-tim)+'ms');
 		 		
 		 		// finish up
 	 			$('#overlay .progress').fadeOut(500, complete);
 			}
 		}
 		
 		
 		// run the interval
 		this.stepInt = window.setInterval(onStep, 1);
 		   
 	},
 	
 	disableView: function() {
 		$(
 			'<div id="overlay">'
	 		+'	<div class="inner">'
	 		+'		<div class="title"></div>'
	 		+'		<div class="status"></div>'
	 		+'		<div class="progress">'
	 		+'			<div class="fill"></div>'
	 		+'		</div>'
	 		+'	</div>'
	 		+'</div>'
 		).appendTo($('body'));
 	},
 	
 	enableView: function() {
 		$('#overlay').fadeOut('fast', function() {$('#overlay').remove();})
 	},
 	
 	/**
 	 * Marks a line with an error class if 
 	 * - it contains the default values (e.g. after createing a blank line)
 	 */
 	markErrors: function(tr) {
 		var def = this.newLineDefaults;
 		var d_start = tr.find('.start .display');
 		var d_end = tr.find('.end .display');
 		var d_text = tr.find('.text .display');
 		if (d_start.text() == def.start || d_end.text() == def.end || d_text.text() == def.text) {
			tr.addClass('error');
		}
 		else {
 			tr.removeClass('error');
 		}
 	},
 	
 	
 	//---------------------------------------------------------------------------------------------
 	//
 	// EDITING FUNCTIONS
 	//
 	//---------------------------------------------------------------------------------------------
 	
 	beginEdit: function(e) { 
 		var td = e.target ? $(e.target).closest('td') : e;
		var tr = td.closest('tr');
		td.find('.display').hide();
		td.find('.edit').show();
		td.find('.input').val( this.lineToText( td.find('.display .value').html() ) ).change().select();
		td.find('.input').bind('keydown', this.onEditKeyPress);
		tr.addClass('edited'); 
 	},
 	onEditKeyPress: function(e) {
 		if (e.keyCode === 27) {
 			SrtEditor.instance.endEdit(e);
 		}
 		if (e.keyCode == 13 && !e.shiftKey) {
 			SrtEditor.instance.saveEdit(e);
 		}
 	},
 	endEdit: function(e) { 
		var tr = $(e.target).closest('tr')
 		var td = $(e.target).closest('td');
		td.find('.input').unbind('keydown', this.onEditKeyPress);
		td.find('.edit').hide();
		td.find('.display').show();
		tr.removeClass('edited'); 		
		this.markErrors(tr);
 	},
 	saveEdit: function(e) {
 		var td = $(e.target).closest('td');
		var tr = $(e.target).closest('tr'); 			

		var old_value = this.stripTrailingBreaks( td.find('.display .value').html() );
		var new_value = this.stripTrailingBreaks( td.find('.input').val() );
		 
		if (new_value != old_value) {
			var srt_id = tr.find('.id').text(); 
	 		var old_line = $.extend({}, this.originalLines[srt_id-1]);
	 		var new_line = $.extend({}, old_line);
	 		new_line[ td.attr('class') ] = new_value;
 
	 		this.originalLines[srt_id-1] = new_line;
	 		this.lines[srt_id-1] = new_line; 
	 		if (this.preview.swf) {
	 			this.preview.swf.changeLine(old_line, new_line);
	 		}
		}
	  
		
		td.find('.display .value').html( this.lineToHtml( new_value )); 

		this.endEdit(e);
		
 	},
 	editCurrentLine: function(e) {
 		var swf = this.preview.element.find('object')[0];
		var line = swf.getCurrentLine();
		if (line.index) {
			$(document).scrollTo( $('#line-'+line.index ), {duration:'short'});
			this.beginEdit( $('#line-'+line.index+' .text') )
		}
		this.preview.element.find('.autoscroll input').attr('checked', false).change();
 	},
 	

 	//---------------------------------------------------------------------------------------------
 	//
 	// LOADING
 	//
 	//---------------------------------------------------------------------------------------------

 	display: function(srt, vim) {  
 		this._current_vimeo = vim;
 		if (srt.indexOf('.srt')!=-1) {
 			this.loadSrt(srt);
 		}
 		else {
 			this.srtLoaded(srt);
 		}
 	},
 	
 	showLoadDialog: function() {
 		this.disableView();
 		var div = $('.loadNew.panel');
 		var self = this;
 		if (!div.hasClass('events-initialized')) {
	 		div.addClass('events-initialized');
	 		
 			div.find('.cancel').click(function(e) {
	 			e.preventDefault();
	 			self.cancelLoadDialog()
	 		});
 			
 			div.find('.load').click(function(e) {
	 			e.preventDefault();
	 			self.doCustomLoad()
	 		});
 			
 			new DropTarget( div.find('textarea')[0] );
 		}
 		$('body').append(div);
 		div.show();
 		div.center();
 		div.draggable();
 		div.resizable({
	 		resize: function() {
 				div.find('input').width( div.width()-40 );
 				div.find('textarea').width( div.width()-40 );
 				div.find('textarea').height( div.height() - div.find('textarea').position().top - 50 );
 			},
	 		minWidth: 100,
	 		minHeight: 100,
	 		stop: function() { div.css('position', 'fixed'); }
 		});
 	}, 
 	
 	
 	cancelLoadDialog: function() {
 		this.enableView();
 		$('.loadNew.panel').hide();
 	},
 	
 	doCustomLoad: function(){
 		
 		var self = this;
 		var div = $('.loadNew.panel');
 		var errors = [];
 		
 		var vim = div.find('input').val();
 		var srt = div.find('textarea').val();
 		 
 		//-----------------------------------------------------------
 		// validate vimeo
 		//-----------------------------------------------------------
 		
 		if (vim.indexOf('vimeo.com/')!=-1) {
 			vim = vim.substr(vim.lastIndexOf('/')+1, vim.length);
 		} 
 		if (!vim || isNaN(vim) || vim.length != 8) {
 			div.find('.vim label').addClass('error'); 
 			errors.push('Invalid Vimeo ID or URL');
 		}
 		else {
 			div.find('.vim label').removeClass('error');
 		}

 		//-----------------------------------------------------------
 		// validate srt
 		//-----------------------------------------------------------
 		
 		 
 		if (!srt || this.srtParser.parse(srt).length == 0) {
 			div.find('.srt label').addClass('error');
 			errors.push('Invalid SRT contents');
 		}
 		else {
 			div.find('.srt label').removeClass('error');
 		}

 		//-----------------------------------------------------------
 		// proceed
 		//-----------------------------------------------------------
 		
 		if (errors.length) {
 			return;
 		}
 		this.display( srt, vim  );
 		this.cancelLoadDialog();
 	},
 	
	loadSrt: function(file) {
 		this.log('loadSrt('+file+')');
 		this.currentSrt = file || this.defaultSrt; 
 		$.ajax({url: this.currentSrt, success: delegate(this, this.srtLoaded)}); 
 		if (this.currentSrt.indexOf('?time=')!=-1) {
 			this.currentSrt = this.currentSrt.substr(0,this.currentSrt.indexOf('?time='))
 		}
 	},
 	srtLoaded: function(data) { 
 		this.currentSrtData = data;
 		this.originalLines = this.srtParser.parse(data); 
 		this.lines = this.originalLines.concat([]);
 		this.updateRows();
 		this.log('srt'+(this.currentSrt ? ' '+this.currentSrt+' ' : ' ')+'loaded. ('+this.lines.length+' lines)')
 		this.element.trigger('srtLoaded', [this.currentSrt, data]);
 	},
 	onresize: function() {
 		
 	},/*
 	onIframeLoaded: function() {
 		if (this.currentSrt) {
 			this.preview.loadSrt(this.currentSrt);
 		}
 		else if (this.currentSrtData) {
 			this.preview.setSrtData(this.currentSrtData);
 		}
// 		if (this.currentSrt && this.currentSrt != this.preview.currentSrt) {
// 			this.preview.loadSrt(this.currentSrt);
// 		}
 	}, */

 
 	onPlayerSubtitleChange: function(e) {   
 	//	console.log('onPlayerSubtitleChange '+e.index)
 		if (this.lastCurrentRow) {
 			this.lastCurrentRow.removeClass('current');
 		}
 		
 		this.lastCurrentRow = $('#line-'+e.index );
 		this.lastCurrentRow.addClass('current');  
 		
 		if (this.preview.element.find('.autoscroll input').attr('checked')) {
			$(document).scrollTo( this.lastCurrentRow, {duration:'short'}); 			
 		}
 	},


 	onTableUpdated: function() {
 		if (this._current_vimeo) {
 			this.preview.load(this._current_vimeo, this.currentSrt, this.currentSrtData);
 			delete this._current_vimeo
 		}
 	},
 	//---------------------------------------------------------------------------------------------
 	//
 	// MANIPULATION
 	//
 	//---------------------------------------------------------------------------------------------
 	
 	newLineDefaults: {
 		start: '00:00:00,000',
 		end: '00:00:00,000',
 		text: 'Default text'
 	},
 	
 	/**
 	 * adds a new row and subtitle line
 	 */
 	addRow: function(e) {
 		var tr, tr_index, target_index 
 
 		tr = $(e.currentTarget).closest('tr');
 		if (tr.length) {
	 		tr_index = Number(tr.find('td.id').text()) - 1; 
	 		target_index = $(e.currentTarget).hasClass('before') ? tr_index : tr_index+1;
 		}
 		else {
 			target_index = this.table.find('tr').length;
 		}
 		var new_line = {
 			id: '',
 			start: this.newLineDefaults.start,
 			end: this.newLineDefaults.end,
 			text: this.newLineDefaults.text
 		};
 		
 		this.lines.splice(target_index, 0, new_line);
 		this.originalLines.splice(target_index, 0, new_line);
 		
 		this.updateRows();
 	},
 	deleteRow: function(e) {
 		tr = $(e.target).closest('tr');
 		var srt_id = Number( tr.find('.id').text() )- 1; 
 		tr.addClass('delete');
 		if (window.confirm('really delete row '+tr.find('.id').text()+'?')) {
 			this.lines.splice(srt_id, 1);
	 		this.originalLines.splice(srt_id, 1);
	 		this.updateRows();
 		}
 		else {
 			tr.removeClass('delete');
 		}
 	},
	displayFontSize: function(v) {
		var s = Number($('html').attr('class').split('zoom-')[1].split(' ')[0]); 
		$('html').removeClass('zoom-'+s);
		var n = s+v;
		if (n>5) { n=5; }
		if (n<1) { n=1; }
		$('html').addClass('zoom-'+n);		
	},
	
	
 	
 	

	//---------------------------------------------------------------------------------------------
 	//
 	// HELPERS
 	//
 	//---------------------------------------------------------------------------------------------
 	
 	lineToText: function(str) {
 		var result = (''+str).replace(/\n/g,'').replace(/<br>/g, '\n');
 		return result;
 	},
 	lineToHtml: function(str) {
 		return (''+str).replace(/\n/g, '<br>'); 
 	},
 	stripTrailingBreaks: function(str) {
 		var result = str;
 		if (str.substr(str.length-4,4) === '<br>') {
 			result = str.substr(0, str.length-4)
 		}
 		else if (str.substr(str.length-1, 1) === '\n') { 
 			result = str.substr(0, str.length-1)
 		} 
 		return result;
 	}
 	
 };